<template>
  <div class="table">
    <!-- 面包屑 -->
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-profile"></i>
          设备列表</el-breadcrumb-item
        >
      </el-breadcrumb>
    </div>

    <!--容器中间部分-->
    <div class="container">
      <!-- 查询操作区域 -->
      <div class="handle-box">
        <el-button
          type="success"
          icon="delete"
          class="handle-del mr10"
          @click="downLoadAllExcel"
        >下载Excel</el-button
        >
        <el-button
          type="danger"
          icon="delete"
          class="handle-del mr10"
          @click="delAll"
          >批量删除</el-button
        >
        <el-button
          type="warning"
          icon="delete"
          class="handle-del mr10"
          @click="delFrozen"
          >批量调整设备状态</el-button
        >
        <el-select
          v-model="account_status"
          placeholder="筛选设备"
          class="handle-select mr10"
          @change="filterEquipment_status"
        >
          <el-option key="-1" label="所有设备" value=""></el-option>
          <el-option v-for="(type,index) in $store.state.filterEquipment_alarm" :key="index" :label="type" :value="type"></el-option>
        </el-select>
        <el-select
                v-model="equipment_type" placeholder="筛选设备" class="handle-select mr10" @change="filterEquipment_type">
          <el-option key="-1" label="所有设备" value=""></el-option>
          <el-option v-for="(type,index) in $store.state.filterEquipment_type" :key="index" :label="type" :value="type"></el-option>
        </el-select>
        <el-select
                v-model="equipment_link" placeholder="筛选设备" class="handle-select mr10" @change="filterEquipment_link">
          <el-option key="-1" label="所有设备" value=""></el-option>
          <el-option v-for="(type,index) in $store.state.filterEquipment_link" :key="index" :label="type" :value="type"></el-option>
        </el-select>
        <el-select
            v-model="equipmentinfo_address" placeholder="筛选设备" class="handle-select mr10" @change="filterEquipment_address">
          <el-option key="-1" label="所有设备" value=""></el-option>
          <el-option v-for="(type,index) in $store.state.filterEquipment_address" :key="index" :label="type" :value="type"></el-option>
        </el-select>
        <el-input
          v-model="searchequipment_name"
          placeholder="通过设备名筛选"
          class="handle-input mr10"
        ></el-input>
        <el-button type="primary" icon="search" @click="search">搜索</el-button>
      </div>
      <!-- 数据展示区域 -->
      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        @selection-change="handleSelectionChange"
        :highlight-current-row="true"
      >
        <el-table-column
          type="selection"
          width="50"
          align="center"
        ></el-table-column>

        <el-table-column label="设备名称" align="center">
          <template slot-scope="scope">
            <p>{{ scope.row.equipmentName }}</p>
          </template>
        </el-table-column>
        <el-table-column label="运行状态" align="center">
          <template slot-scope="scope">
            <div slot="reference" class="name-wrapper" style="cursor: pointer">
              {{ scope.row.alarmType }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="位置" align="center">
          <template slot-scope="scope">
            <div slot="reference" class="name-wrapper" style="cursor: pointer">
                {{ scope.row.address }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-link @click="selectToWork(scope.row.id, scope.row)" type="info">开始工作</el-link> /
            <el-link @click="updateEquipment(scope.row.id, scope.row)"  type="success">修改设备信息</el-link> /
            <el-link @click="deleteEquipment(scope.row.id, scope.row)"  type="danger">删除设备</el-link>
          </template>
        </el-table-column>
      </el-table>
      <!--分页部分-->
      <div class="pagination">
        <el-pagination
          background
          @current-change="handleCurrentChange"
          layout="prev, pager, next"
          :total="totalSize"
        >
        </el-pagination>
      </div>
    </div>
    <Form @close="close" @commitUidAndAddress="commitUidAndAddress" :editInfo="editInfo" :hoverEquipmentInfo="hoverEquipmentInfo" :isShow="isShow" @update1="update1" v-if="isShow"/>
  </div>
</template>

<script>
import userApi from "../../api/user";
import Form from "@/components/page/Form.vue"
export default {
  components: {Form},
  data() {
    return {
      equipment_link: "连接类型",
      equipment_type: "设备类型",
      account_status: "设备状态", // select框筛选项
      equipmentinfo_address: "设备地址",
      tableData: [],
      totalSize: 0,
      cur_page: 1,
      multipleSelection: [], // 选中的列，里面是一个个对象，每个对象里面是该列的所有值
      searchequipment_name: "", // 搜索关键字
      del_list: [],
      isShow: false,
      editInfo: false,
      hoverEquipmentInfo:{},
      Condition:{pageNum: 1, data: {} },
      ids: [],
      options: [{
        value: '选项1',
        label: '1楼'
      }, {
        value: '选项2',
        label: '2楼'
      }, {
        value: '选项3',
        label: '3楼'
      }, {
        value: '选项4',
        label: '4楼'
      }, {
        value: '选项5',
        label: '5楼'
      }]
    };
  },
  created () {
    this.mycreate_search()
  },
  methods: {
    async mycreate_search(){
      await this.create_search()
    },
    // 初始查询
    create_search(){
      return new Promise((resolve,reject) => {
        this.Condition = {pageNum: 1, data: {}}
        userApi.queryByCondition(this.Condition).then((response) => {
          this.tableData = response.data.data.list;
          this.totalSize = response.data.data.total;
        });
        resolve()
      })
    },

    // 点击翻页
    handleCurrentChange(val) {
      // 获取当前页数
      this.cur_page = val;
      this.search()
    },

    // All search
    async allSearch(){
      await this.search()
    },
    // 通用搜索  默认把查询
    search() {
      return new Promise((resolve,reject) => {
        this.Condition.data['equipmentName'] = this.searchequipment_name
        this.Condition.pageNum = this.cur_page
        console.log(this.Condition)
        userApi.queryByCondition(this.Condition).then((response) => {
          console.log(response.data.data)
          this.tableData = response.data.data.list;
          this.totalSize = response.data.data.total;
        });
        resolve()
      })
    },

// 下拉框筛选
    // 通过状态筛选
    filterEquipment_status(val) {
      this.Condition.data['alarmType'] = val;
      this.allSearch();
    },

    // 通过类型筛选
    filterEquipment_type(val) {
      this.Condition.data['equipmentType'] = val;
      this.allSearch();
    },

    // 通过连接类型筛选
    filterEquipment_link(val){
      this.Condition.data['linkType'] = val;
      this.allSearch();
    },
    // 根据地址筛选设备
    filterEquipment_address(val){
      this.Condition.data['address'] = val;
      this.allSearch();
    },

    // 选中操作
    handleSelectionChange(val) {
      const valid = []
      val.forEach((item)=>{
        valid.push(item.equipmentId)
      })
      this.multipleSelection = valid
    },

    // 执行删除所有选中的列
    async delAll() {
      await this.$confirm("这些设备将永久删除，是否继续？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
      }).then(() => {
        userApi.delete_equipment(this.multipleSelection).then((response) => {
          this.$notify({
            title: response.data.flag ? "删除成功" : "删除失败",
            type: response.data.flag ? "success" : "error",
            message: response.data.message,
          });
          if (response.data.flag) {
            this.search()
          }
        });
      });
    },

    // 批量修改状态
    async delFrozen() {
      await this.$confirm("这些设备将会永久修改状态，是否继续？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
      }).then(() => {
        userApi.changeStatus(this.multipleSelection).then((response) => {
          this.$notify({
            title: response.data.flag ? "修改成功" : "修改失败",
            type: response.data.flag ? "success" : "error",
            message: response.data.message,
          });
          if (response.data.flag) {
            this.search()
          }
        });
      });
    },

    // 删除单个账号
    async deleteEquipment(id, row) {
      await this.$confirm("该设备将永久删除，是否继续？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
      }).then(() => {
         this.ids = [id]
         userApi.delete_equipment(id).then((response) => {
          this.$notify({
            title: response.data.flag ? "删除成功" : "删除失败",
            type: response.data.flag ? "success" : "error",
            message: response.data.message,
          });
          if (response.data.flag) {
            const index = this.tableData.indexOf(row);
            this.tableData.splice(index, 1);
          }
        });
      });
    },

    // 查询单个设备的信息
    selectToWork(id, row) {
      this.editInfo = false
      this.isShow = !this.isShow
      this.hoverEquipmentInfo = row
    },

    // 当点击单个设备 ==修改== 按钮的时候弹窗  获取子组件传递的参数
    updateEquipment(id, row) {
      this.editInfo = true
      this.isShow = !this.isShow
      this.hoverEquipmentInfo = row
    },

    // 直接进行更新 弹窗
    async update1(val) {
      await userApi.update_equipment(val).then(response=>{
        if (response.data.flag) {
          this.$notify.success({
            title: '成功',
            message: response.data.message,
          });
          this.create_search()
        } else {
          this.$notify.error({
            title: '失败',
            message: response.data.message,
          });
        }
      })
    },

    // 开始工作  返回用户输入的id和设备的地址名称
    async commitUidAndAddress(row,uid){
      const val = {
        userId: uid,
        addressName: row.addressName
      }
      await userApi.commitUidAndAddress(val).then(response=>{
        if (response.data.flag) {
          this.$notify.success({
            title: '成功',
            message: response.data.message,
          });
          this.create_search()
        } else {
          this.$notify.error({
            title: '失败',
            message: response.data.message,
          });
        }
      })
    },

    // 通用关闭
    close(){
      this.isShow = !this.isShow
    },
    // 下载Excel
    downLoadAllExcel() {
      console.log("下载excel")
      userApi.downLoadExcel().then((res) => {
        console.log(res)
          if (!res) return
          // console.log("res data = "+res.data);
          let blob = new Blob([res.data], {type: 'application/vnd.ms-excel;charset=utf-8'}) // 文件类型
          // console.log(res.headers)
          // console.log(res.headers['content-disposition']); // 从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx") 设置的文件名;
          //以=分割取数组[1]元素为文件名
          let filename = window.decodeURI(res.headers['content-disposition'].split('=')[1])
          let url = window.URL.createObjectURL(blob);  // 创建下载链接
          let aLink = document.createElement("a");    // 赋值给a标签的href属性
          aLink.style.display = "none";
          aLink.href = url;
          aLink.setAttribute("download", filename);
          document.body.appendChild(aLink);   // 将a标签挂载上去
          aLink.click();          // a标签click事件
          document.body.removeChild(aLink);  // 移除a标签
          window.URL.revokeObjectURL(url);   // 销毁下载链接
          return this.$message.success("导出设备信息成功");
      }).catch(function (error) {
        console.log(error);
      });
    }
  },
};
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 200px;
  display: inline-block;
}

.del-dialog-cnt {
  font-size: 16px;
  text-align: center;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}
</style>
